package sdk.webview.fmc.com.fmcsdk.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import sdk.webview.fmc.com.fmcsdk.R;
import sdk.webview.fmc.com.fmcsdk.base.BaseActivity;
import sdk.webview.fmc.com.fmcsdk.base.BasePresenter;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.Utility;
import sdk.webview.fmc.com.fmcsdk.util.XLog;
import sdk.webview.fmc.com.fmcsdk.view.LoginFrameStyleColorButton;

/**
 * 服务器地址设置
 */
public class ConnectSettingActivity extends BaseActivity implements View.OnClickListener {
    EditText address;
    LoginFrameStyleColorButton ok_btn;
    TextView tv_title;
    ImageView ivBack;
    final int SCAN_CODE = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_connect_setting;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        address = (EditText) findViewById(R.id.address);
        tv_title = (TextView) findViewById(R.id.tv_title);
        ivBack = (ImageView) findViewById(R.id.iv_back);
        ok_btn = (LoginFrameStyleColorButton) findViewById(R.id.connect_ok);
        //如果用户在上一个界面选择的是扫码，则打开扫码界面，然后将数据返回到这里
        boolean isScan = getIntent().getBooleanExtra("isScan", false);
        if (isScan) {
            Intent intent = new Intent(context, CaptureActivity.class);
            intent.putExtra("bletooth","0");
            startActivityForResult(intent, SCAN_CODE);
        }

        tv_title.setText(getString(R.string.address_setting));
        /**如果地址不是空的加载存储的地址*/
        if (!TextUtils.isEmpty(sharedPrefs.getString(Constant.BASE_ADDRESS_URL, ""))) {
            address.setText(sharedPrefs.getString(Constant.BASE_ADDRESS_URL, ""));
        }
        ok_btn.setOnClickListener(this);
        ivBack.setOnClickListener(this);
    }


    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    public void onClick(View v) {
        if (v == ok_btn) {
            if (getText(address).isEmpty()) {
                ToastMessage(R.string.address_not_null);
            } else {
                if (getText(address).length() < 15) {
                    ToastMessage(R.string.input_ok_adderss);
                    return;
                }
                if (!getText(address).substring(0, 7).equalsIgnoreCase("http://") && !getText(address).substring(0, 8).equalsIgnoreCase("https://")) {
                    ToastMessage(R.string.input_ok_adderss);
                    return;
                }
                //如果地址的末尾是"/"把他去除
                String text = getText(address);
                SharedPreferences.Editor editor = sharedPrefs.edit();
                if (text.substring(text.length() - 1).equals("/")) {
                    editor.putString(Constant.BASE_ADDRESS_URL, text.substring(0, text.length() - 1));
                } else {
                    editor.putString(Constant.BASE_ADDRESS_URL, text);
                }
                editor.apply();
                finish();
            }
        } else if (v == ivBack) {
            finish();
        }
    }

    //扫描二维码获取host和port
    public void scanaddress(View view) {
        Intent intent = new Intent(context, CaptureActivity.class);
        intent.putExtra("bletooth","0");
        startActivityForResult(intent, SCAN_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == SCAN_CODE) {
//                //扫到的链接
                String result = data.getStringExtra(CaptureActivity.SCAN_RESULT);
                XLog.i(result);
                if (!result.startsWith("http")) {
                    ToastMessage(R.string.please_scan);
                } else {
                    int characterPosition = getCharacterPosition(result);
                    if (characterPosition < 2) {//如果少于两个斜杠就视为无效地址
                        ToastMessage(R.string.please_scan);
                    } else if (characterPosition == 2) {
                        address.setText(result);//如果只有两个斜杠就显示全路径
                    } else {
                        String appName = (String) Utility.getMetaData(context, Constant.APP_NAME);
                        if (result.contains("/fmc")&&!Constant.APP_NAME_ZY.equals(appName)){
                            address.setText(initHostPrefix(result));
                        }else {
                            address.setText(result.substring(0, characterPosition));//如果有三个以上斜杠就截取第三个斜杠
                        }
                    }
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 获取第三次出现斜杠的位置
     *
     * @param string
     * @return
     */
    public static int getCharacterPosition(String string) {
        //这里是获取"/"符号的位置
        Matcher slashMatcher = Pattern.compile("/").matcher(string);
        int mIdx = 0;
        while (slashMatcher.find()) {
            mIdx++;
            //当"/"符号第三次出现的位置
            if (mIdx == 3) {
                break;
            }
        }
        if (mIdx < 3) {
            return mIdx;
        } else {
            return slashMatcher.start();
        }
    }



        public  String initHostPrefix(String url) {
            if (url.contains("/fmc")) {
                String prefix = extractHostPrefix(url);
                return prefix;
            }
            // 如果不需要初始化，可以返回默认值或者null
            return null;
        }



        private  String extractHostPrefix(String url) {
            int endIndex = url.indexOf("/fmc") + 4;
            return url.substring(0, endIndex);
        }

}